<template>
  <view class="container">
    <view class="user-list flex items-center justify-between">
      <text class="list-name">店铺名称</text>
      <view class="flex">
        <input class="list-val" v-model="form.shopName" disabled placeholder-style="color:#101010;fontSize:28rpx" />
      </view>
    </view>
    <view class="user-list flex items-center justify-between">
      <text class="list-name">收货人</text>
      <view class="flex">
        <input class="list-val" v-model="form.name" placeholder="请输入收货人"
          placeholder-style="color:#101010;fontSize:28rpx" />
      </view>
    </view>
    <view class="user-list flex items-center justify-between">
      <text class="list-name">手机号</text>
      <view class="flex">
        <input class="list-val" v-model="form.phone" placeholder="请输入手机号"
          placeholder-style="color:#101010;fontSize:28rpx" />
      </view>
    </view>
    <view class="user-list flex items-center justify-between" @tap="onAreaShow">
      <text class="list-name">地区</text>
      <view class="flex">
        <text class="list-val">{{ areaText || "请选择地区~" }}</text>
      </view>
    </view>
    <view class="user-list flex items-center justify-between">
      <text class="list-name">详细地址</text>
      <view class="flex">
        <input class="list-val" v-model="form.detailAddress" placeholder="请输入详细地址"
          placeholder-style="color:#101010;fontSize:28rpx" />
      </view>
    </view>

    <view class="user-list flex items-center justify-between">
      <text class="list-name">设为默认地址</text>
      <view class="flex" @click.stop="onCheckDefault">
        <image class="icon-width mr-20" v-if="form.isDefault" :src="IMG_URL2 + 'login/checkbox1.svg'"></image>
        <image class="icon-width mr-20" v-else :src="IMG_URL2 + 'login/checkbox.svg'"></image>
      </view>
    </view>

    <view class="button-box px-48">
      <view class="exit-login bg2" @click="onAddEditAddress" :disabled="loading">
        <up-loading-icon class="loading" color="#fff" size="16" :show="loading"></up-loading-icon><text>保存收货地址</text>
      </view>
      <view class="del" v-if="shopReceiveId != '' && shopReceiveId != null" @click="delAddress" :disabled="loading1">
        <up-loading-icon class="loading" color="#000" size="16" :show="loading1"></up-loading-icon><text>删除收货地址</text>
      </view>

      <up-picker :show="show" ref="uPickerRef" :columns="areaList" keyName="name" @confirm="confirm"
        @change="changeHandler" @cancel="show = false" />
    </view>
  </view>
</template>

<script setup>
import { IMG_URL2 } from "@/config";
import { computed, ref, reactive, onBeforeMount, } from 'vue';
import { shopApi } from "@/api";
import test from '@/superant/helper/test.js';
import $helper from '@/superant/helper';

const province = ref("北京市");
const city = ref("北京市");
const area = ref("东城区");
let shopReceiveId = ref(null)
const loading = ref(false);
const loading1 = ref(false);
const form = reactive({
  address: "",
  city: '',
  cityCode: "",
  detailAddress: "",
  isDefault: false,
  name: "",
  phone: "",
  province: "",
  provinceCode: "",
  shopName: "",
  street: "",
  streetCode: ""
});


let show = ref(false);
let defaultAddress = ref([])  //默认选中 (回填时或者初次显示默认选中)
let addressData = ref([])  //原始数据 (引入的json文件)
let areaList = ref([[], [], []])
let areaText = ref('')

const getMapData = () => {
  shopApi.GETMAP().then((res) => {
    if (res.code == 200) {
      addressData.value = res.result;
      onShowCurrent()
    } else {
      uni.showToast({
        title: res.errMsg,
        icon: "success",
      });
    }
  })
}
const uPickerRef = ref(null)
// change事件 当选择值变化时触发	
const changeHandler = (e) => {
  const { columnIndex, value } = e
  console.log(value, 'value')
  let city = value[0].childrens
  if (columnIndex === 0) { // 省变化更新市、区列表
    // setColumnValues(index, setVal) 设置对应列的选择值
    uPickerRef.value.setColumnValues(1, city);
    uPickerRef.value.setColumnValues(2, city[0].childrens);
  } else if (columnIndex === 1) { // 市变化更新区/县列表
    uPickerRef.value.setColumnValues(2, value[1].childrens);
  }
}

// 确认事件
const confirm = (e) => {
  let { value } = e
  areaText.value = `${value[0].name}-${value[1].name}-${value[2].name}`
  // code
  form.province = value[0].name //省
  form.provinceCode = value[0].code
  // 市
  form.city = value[1].name
  form.cityCode = value[1].code
  //区
  form.street = value[2].name
  form.streetCode = value[2].code
  show.value = false // 关闭弹框
}

const onShowCurrent = () => {
  //省的数组
  const provinceData = addressData.value.map(e => {
    return { name: e.name, code: e.code }//这里可以直接return e.name  这里我是要用到code所以才用对象包起来的 下面的市 区 也一样
  })
  //市的数组
  const cityData = addressData.value.map(e => {
    const arr = []
    arr.push(
      e.childrens.map(c => {
        return { name: c.name, code: c.code }
      })
    )
    return arr
  })
  //区的数组
  const areaData = addressData.value.map(e => {
    const arr = []
    arr.push(
      e.childrens.map(c => {


        if (c.childrens && c.childrens.length > 0) {
          c.childrens.map(d => {
            return { name: d.name, code: d.code }
          })
        } else {
          c.childrens = []
        }
      }

      )
    )
    return arr
  })
  // const arr = [provinceData, cityData[0][0], areaData[0][0][0]]

  areaList.value[0].push(...addressData.value) // 省
  areaList.value[1].push(...areaList.value[0][0].childrens) // 市
  areaList.value[2].push(...areaList.value[1][0].childrens) // 区


}

onLoad(async (options) => {
  await getMapData()
  uni.setNavigationBarTitle({
    title: options.id ? "修改地址" : "新增地址"
  });
  // 编辑回显
  if (options.id) {
    shopReceiveId.value = options.id
    getDetails(options.id)
  }

  getShopData()


});

const getDetails = (Id) => {
  shopApi.SHOPRECEIVEGETDETAILBYID({ id: Id }).then((res) => {
    if (res.code == 200) {
      form.address = res.result.address
      form.city = res.result.city
      form.cityCode = res.result.cityCode
      
      form.isDefault = res.result.isDefault
      form.name = res.result.name
      form.phone = res.result.phone
      form.province = res.result.province
      form.provinceCode = res.result.provinceCode
      form.shopName = res.result.shopName
      form.street = res.result.street
      form.streetCode = res.result.streetCode
      form.detailAddress = res.result.detailAddress

      console.log(res.result, 'res.result')

      areaText.value = `${res.result.province}-${res.result.city}-${res.result.street}`
    } else {
      uni.showToast({
        title: res.errMsg,
        icon: "success",
      });
    }

  })
}

const onAreaShow = () => {
  show.value = true;
  areaList[1].push(...areaList[0][0].childrens) // 市
  areaList[2].push(...areaList[1][0].childrens) // 区

};


// 设为默认地址
const onCheckDefault = () => {
  form.isDefault = form.isDefault == true ? false : true;
};

const getShopData = () => {
  shopApi.SHOPGETCURRENTSHOPINFO().then((res) => {
    if (res.code == 200) {
      form.shopName = res.result.name
    } else {
      uni.showToast({ title: res.errMsg, icon: "none" });
    }

  })
}

// 添加&&编辑收货地址
const onAddEditAddress = () => {
  if (form.name == "") {
    uni.showToast({
      title: "请输入收货人",
      icon: "none",
      mask: true
    });
    return;
  }
  if (form.phone == "") {
    uni.showToast({
      title: "请输入手机号",
      icon: "none",
      mask: true
    });
    return;
  }
  if (!test.mobile(form.phone)) {
    $helper.toast('请输入正确的手机号');
    return;
  }
  if (form.detailAddress == "") {
    uni.showToast({
      title: "请输入详细地址",
      icon: "none",
      mask: true
    });
    return;
  }

  let params = {
    address: form.address,
    city: form.city,
    cityCode: form.cityCode,
    detailAddress: form.detailAddress,
    isDefault: form.isDefault,
    name: form.name,
    phone: form.phone,
    province: form.province,
    provinceCode: form.provinceCode,
    shopName: form.shopName,
    street: form.street,
    streetCode: form.streetCode,
  }
  if (shopReceiveId.value) {
    params.shopReceiveId = shopReceiveId.value
  }
  loading.value = true;
  shopApi.SHOPRECEIVEGSAVEORUPDATE(params)
    .then((res) => {
      loading.value = false;
      if (res.code == 200) {
        if (form.id) {
          uni.showToast({
            title: "修改成功",
            icon: "success",
            mask: true
          });
          uni.navigateBack();
        } else {
          uni.showToast({
            title: "新增成功",
            icon: "success",
            mask: true
          });
          uni.navigateBack();
        }
      } else {
        uni.showToast({
          title: res.errMsg,
          icon: "success",
        });
      }
    });
};
const delAddress = () => {
  loading1.value = true;
  shopApi.SHOPRECEIVEGBATCHDELETE({ ids: [shopReceiveId.value] }).then((res) => {
    loading1.value = false;
    if (res.code == 200) {
      uni.showToast({ title: '删除成功', icon: "none" });
      setTimeout(() => {
        uni.navigateBack();
      }, 1000)
    } else {
      uni.showToast({
        title: res.errMsg,
        icon: "success",
      });
    }

  })
}
</script>

<style lang="scss">
page {
  background-color: #ffffff;
}
</style>
<style lang="scss" scoped>
.vmall-address-add {
  .container {
    border-radius: 24rpx;
  }

  .cell {
    display: flex;
    align-items: center;
    padding: 20rpx 0rpx;
    border-bottom: 2rpx solid #E6E6E6;
    justify-content: space-between;

    .title {
      width: 120rpx;
    }
  }



  .default-tip {
    color: #606266;
    vertical-align: text-top;
  }

  .btn-fixed {
    position: fixed;
    bottom: 0;
    width: 100%;
    margin: 0 auto;
    background: #ffffff;
    box-sizing: border-box;
  }

  .save-btn {
    width: 100%;
    height: 84rpx;
    line-height: 84rpx;
    background: rgba(214, 142, 68, 1);
    color: #ffffff;
    text-align: center;
    border-radius: 30px 30px 30px 30px;
  }

  :deep(.u-input) {
    border: 0;
    background: #ffffff !important;
  }

  :deep(.uni-input-wrapper) {
    font-size: 28rpx;
  }

  :deep(.u-textarea) {
    border: 0;
  }

  :deep(.uni-textarea-wrapper) {
    font-size: 28rpx;
  }
}

.container {
  .icon-width {
    width: 40rpx;
    height: 40rpx;
    vertical-align: text-top;
  }

  .info-head {
    .info-title {
      line-height: 60rpx;
      font-size: 28rpx;
      font-weight: 600;
      color: #333333;
    }

    .save-btn {
      color: #fff;
      background: linear-gradient(90deg, rgba(233, 180, 97, 1), rgba(238, 204, 137, 1));
      width: 100rpx;
      border-radius: 30rpx;
      height: 60rpx;
      line-height: 60rpx;
      font-size: 28rpx;
    }

    .dis-btn {
      opacity: 0.5;
    }
  }


  // 个人信息项
  .user-list {
    background: #fff;
    height: 100rpx;
    border-bottom: 1rpx solid #f6f6f6;
    padding: 0 20rpx;
    box-sizing: border-box;
    .list-name {
      font-size: 32rpx;
      color: rgba(0, 0, 0, 0.6);
    }

    .avatar {
      width: 67rpx;
      height: 67rpx;
      border-radius: 50%;
    }

    .list-val {
      color: #101010;
      font-size: 28rpx;
      text-align: right;
    }

    .chevronright {
      width: 32rpx;
      height: 32rpx;
      margin-left: 10rpx;
    }

  }

  .button-box {
    width: 100%;
    position: fixed;
    bottom: 50rpx;
    left: 0;
    z-index: 9;
    background-color: #fff;
    text-align: center;

    .del {
      width: 654rpx;
      font-family: PingFang SC;
      font-size: 14px;
      font-weight: 400;
      line-height: 22px;
      color: rgba(0, 0, 0, 0.6);
      margin-top: 30rpx;
      margin-bottom: 40rpx;
      display: flex;
      justify-content: center;
    }
  }

  .exit-login {
    width: 654rpx;
    height: 92rpx;
    line-height: 92rpx;
    background: #D68E44;
    color: #ffffff;
    text-align: center;
    border-radius: 64px;
    font-size: 32rpx;
    display: flex;
    justify-content: center;
  }

  .exit-login:after {
    border: none;
  }

  .tips {
    font-size: 16px;
    font-weight: 400;
    line-height: 24px;
    text-align: right;
    text-underline-position: from-font;
    text-decoration-skip-ink: none;
    color: rgba(145, 74, 0, 1);
    padding: 24rpx;
    box-sizing: border-box;
  }
}
</style>
